# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_ningde_zfxxgk_policy'

    province = '福建省'
    city = '宁德市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)
    custom_settings = {
        "DEFAULT_REQUEST_HEADERS": {
            "Accept": "text/plain, */*; q=0.01",
            "Accept-Language": "zh,en;q=0.9,zh-CN;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Origin": "https://www.ningde.gov.cn",
            "Pragma": "no-cache",
            "Referer": "https://www.ningde.gov.cn/zfxxgkzl/zfxxgkml/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
            "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\""
        }
    }

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                "CONCURRENT_REQUESTS": 5,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": None,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        source = '宁德市人民政府'
        county = ''
        # for source, county, url in [
        #     ["宁德市人民政府", "", "https://www.ningde.gov.cn/zfxxgkzl/zfxxgkml/"],
        # ]:
        #     yield scrapy.Request(url, callback=self._parser_dataproxy_html,
        #                          meta={"item": {'source': source, 'county': county}})

    # def _parser_dataproxy_html(self, response):
        meta = {"item": {'source': source, 'county': county}}
        data = {
            'channelid': '205142',
            'templet': 'docswj.jsp',
            'sortfield': '-docreltime',
            'classsql': 'chnlid=36874,38170,3734,3735,3737,3732,3740,3733,3731,3730,3741,3744,3756,3758,*modal=1',
            'page': '1',
            'prepage': '50'
        }
        url = 'https://www.ningde.gov.cn/was5/web/search'
        # if url[-1] != "?":
        #     url += "?"
        # temp_url = url + urllib.parse.urlencode(data)
        meta.update({
            "data": data,
            "url": url,
        })
        print(data)
        yield self.FormRequest(
            url,
            formdata=data,
            method="POST",
            callback=self.parse_list,
            dont_filter=True,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        data = json.loads(response.text.replace('\n', ''))
        url_list = data['docs']
        for elem in url_list:
            if elem.get('url') == '链接':
                continue
            item = Item()
            item['source_url'] = elem['docpuburl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubdate'].replace("年", "-").replace("月", "-")[:-1]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(item['publish_date'], response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_page = math.ceil(int(data['count']) / 50)
        print(meta['data'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1))[:16]:
            data = meta.get("data")
            data['page'] = str(page)
            url = meta.get('url')
            # temp_url = url + urllib.parse.urlencode(data)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {data}")
            yield self.FormRequest(
                url,
                formdata=data,
                method="POST",
                callback=self.parse_list,
                dont_filter=True,
                meta=meta
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_ningde_zfxxgk_policy -a get_next=0".split())
